import React from 'react'
import { WingBlank, WhiteSpace, NavBar, Button, Icon, List, InputItem, Toast } from 'antd-mobile'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'

import Logo from '../../component/logo/logo'
import {register} from "../../redux/actions"

class Register extends React.Component {

    back = () => {
        this.props.history.goBack()
    }

    toLogin = () => {
        this.props.history.push("/login")
    }

    register = () => {
        var { userName, password, password2 } = this.state;
        if (password !== password2) {
            return Toast.fail("两次密码不相同!", 1)
        }
        if (!(userName && password && password2)) {
            return Toast.fail("请填写账号和密码!", 1)
        }
        this.props.register({ userName, password });
    }


    handleChange = (field, value) => {
        this.setState({
            [field]: value
        })
    }

    render() {
        var {id,errorMessage}=this.props.user
        if(id){
            //登陆后重定向
            return <Redirect to="/"/>
        }
        return (
            <div>
                <NavBar
                    mode="light"
                    icon={<Icon type="left" onClick={this.back} />}
                    onLeftClick={this.onOpenChange}
                >注册</NavBar>
                <WingBlank>
                    <Logo />
                    <div className="error-holder">{errorMessage}</div>
                    <List>
                        <InputItem clear placeholder='请输入账号' onChange={(value) => this.handleChange("userName", value)}>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：</InputItem> <WhiteSpace />
                        <InputItem type='password' clear placeholder='请输入密码' onChange={(value) => this.handleChange("password", value)}>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码：</InputItem><WhiteSpace />
                        <InputItem type='password' clear placeholder='请输入密码' onChange={(value) => this.handleChange("password2", value)}>确认密码：</InputItem><WhiteSpace />
                        <Button type="primary" onClick={this.register}>注册</Button><WhiteSpace />
                        <Button onClick={this.toLogin}>已有账号，去登陆</Button>
                    </List>
                </WingBlank>
            </div>
        )
    }

}

export default connect(state => ({ user: state.user }),{register})(Register)